package bavaria.hightech.banking.time;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import bavaria.hightech.banking.bank.BankCustomerView;
import bavaria.hightech.banking.exceptions.FixedDepositException;

/**
 * class TimeServer
 * @author David
 *
 */
public class TimeServer {

	private static final Calendar myCalendar = Calendar.getInstance();
	private static final int factorInSeconds = 24 * 60 * 60;
	private static int stopAfterLoops = 120;
	private static BankCustomerView b = null;

	private TimeServer() {
	}

	/**
	 * set the CallbackInterface
	 * @param c
	 */
	public static final void setCallbackInterface(BankCustomerView c) {
		b = c;
	}

	public static final void doIt() {
		try {
			b.applyInterests();
		} catch (FixedDepositException e) {
			e.printStackTrace();
		}
		String[] stra = b.listAccs();
		for (String str : stra)
			System.out.println(str);
	}

	/**
	 * get a clone of the current calendar
	 * @return
	 */
	public static final Calendar getCalendar() {
		return (Calendar) myCalendar.clone();
	}
	
	/**
	 * calls the startTiming-method of the TimeSever-class
	 */
	public static void init() {
		new TimeServer().startTiming();
	}

	/**
	 * modify the Calendar by calling the add-method of it
	 */
	private void modifyCalendar() {
		myCalendar.add(Calendar.SECOND, 1 + factorInSeconds);
		// System.out.println(myCalendar.getTime());
	}

	/**
	 * start the time
	 */
	private void startTiming() {
		Timer timer = new Timer();
		timer.scheduleAtFixedRate(new TimerTask() {
			@Override
			public void run() {
				doIt();
				TimeServer.this.modifyCalendar();
				if (--stopAfterLoops == 0) {
					this.cancel();
				}
			}
		}, 5000, 1000);
	}
}
